package handler

import (
	"blog2/database"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Comment struct {
	CommentText string `json:"commenttext"`
	UserName    string `json:"username"`
}

func PublishComment(c *gin.Context) {
	var tmpcomment Comment
	if err := c.ShouldBindJSON(&tmpcomment); err != nil {
		c.JSON(200, gin.H{"msg": "invalid request", "code": 400})
		return
	}
	username := tmpcomment.UserName
	commenttext := tmpcomment.CommentText
	id := c.Param("id")
	blogId, err := strconv.Atoi(id)
	if err != nil {
		c.JSON(200, gin.H{"msg": "invalid blog id", "code": 400})
		return
	}
	user := database.GetUserByName(username)
	uid := user.Id
	err = database.CreateComment(blogId, uid, commenttext)
	if err != nil {
		c.JSON(200, gin.H{"msg": "error creating comment", "code": 500})
		return
	}
	// save comment to database
	c.JSON(200, gin.H{"status": "Comment posted", "code": 200})
}
